#!/bin/python

import os

HOME_DIR = f'{os.getcwd()}'
BUS_NAME = 'ysyx_rv32'
FILE_NAME = f'nic400_{BUS_NAME}'
AMBA_DIR = f'{BUS_NAME}_RTL/logical/nic400_{BUS_NAME}'
LPAT_PATH = './../../'
SPAT_PATH = './'

os.system('rm -rf ../amba')
os.system('mkdir ../amba')
os.chdir('../../demo')
os.system('git pull')
os.system(f'rm -rf {BUS_NAME}_RTL')
os.system(f'unzip {BUS_NAME}_RTL.zip')
os.system(f'cp -rf {AMBA_DIR}/* {HOME_DIR}/../amba/')
os.chdir(f'{HOME_DIR}')


def work(val) -> str:
    if len(val) > 1:
        if LPAT_PATH in val[1]:
            val[1] = f'../amba/{val[1][len(LPAT_PATH):]}'
        elif SPAT_PATH in val[1]:
            val[1] = f'../amba/nic400/verilog/{val[1][len(SPAT_PATH):]}'
        # print(val[1])
        return f'{val[1]}'
    else:
        if SPAT_PATH in val[0]:
            val[0] = f'../amba/nic400/verilog/{val[0][len(SPAT_PATH):]}'
        # print(val[0])
        return f'{val[0]}'


src_res = ''
inc_res = ''
with open(f'../amba/nic400/verilog/{FILE_NAME}.vc', 'r',
          encoding='utf-8') as fp:
    for v in fp:
        if '-v' in v or f'{FILE_NAME}.v' in v:
            if '//' in v:
                continue
            tmp = v.split()
            src_res += f'{work(tmp)}\n'
        elif '+incdir+' in v and './' in v:
            demo = v[:len('+incdir+')] + ' ' + v[len('+incdir+'):]
            # print(f'demo: {demo}')
            tmp = demo.split()
            inc_res += f'+incdir+{work(tmp)} \\\n'

# print(inc_res)
with open('../filelist/amba.f', 'w+', encoding='utf-8') as fp:
    fp.writelines(src_res)

with open('inc_res', 'w+', encoding='utf-8') as fp:
    fp.writelines(inc_res)
